<template>
  <div>
    <!-- 碎片列表 -->
    <my-breadcrumb :items="['富文本帖子管理', '帖子管理']"/>
    <search :formItems='searchItems' @search='getList' :check="true" ref='search' />
    <el-button @click="isAdd = true; showAdd = true; cleanForm();loading = false" type="primary" class="marginBottom10" > 发布富文本帖子 </el-button>
    <el-table :data='tableData' @sort-change="sortChange" style='width: 100%'>
      <el-table-column type="index" label='序号' ></el-table-column>
      <el-table-column prop='membername' label='发布人' ></el-table-column>
      <el-table-column prop='createtime' label='发布时间' ></el-table-column>
      <el-table-column prop='title' label='帖子标题'></el-table-column>
      <el-table-column prop='content' width="300px" label='帖子简介'></el-table-column>
      <el-table-column prop='fabulous' sortable label='点赞数' ></el-table-column>
      <el-table-column prop='trampled' sortable label='被踩数' ></el-table-column>
      <el-table-column prop='collcount' sortable label='收藏量'></el-table-column>
      <el-table-column prop='clickcount' sortable label='阅读量'></el-table-column>
      <el-table-column prop='commentcount' sortable label='评论量'></el-table-column>
      <el-table-column prop='ishot' sortable label='是否热门' >
        <template slot-scope="scope">
          <span v-if="!Number(scope.row.ishot)">否</span>
          <span v-if="Number(scope.row.ishot)">是</span>
        </template>
      </el-table-column>
      <el-table-column prop='fragmentcount' label='操作'>
        <template slot-scope="scope">
          <span class="astyle"  @click="handleClickEditItem(scope.row.id)">编辑</span>
          <span class="dstyle"  @click="handleClickDeleteItem(1, scope.row.id)">删除</span>
          <span class="astyle"  @click="hanldeClickCheckItem(scope.row.id)">查看评论</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.page"
        :page-sizes="[20, 50, 100]"
        :page-size="page.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>

    <el-dialog
      :title="isAdd ? '发布富文本帖子' : '富文本帖子编辑'"
      :close-on-click-modal="false"
      width="70%"
      :visible.sync="showAdd">
        <el-form ref="richForm" :rules="rules" label-position="left" :model="formData" label-width="110px">
          <el-form-item label="发布人" prop="memberid" >
            <el-select
              class="width100"
              v-model="formData.memberid"
              filterable
              :clearable="true"
              remote
              reserve-keyword
              placeholder="请输入关键词"
              :remote-method="getMember"
              :loading="loading">
              <el-option
                v-for="item in memberArr"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <!-- <el-input v-model="formData.membername"></el-input> -->
          </el-form-item>

          <el-form-item label="标题" prop="title" >
            <el-input v-model="formData.title"></el-input>
          </el-form-item>

          <el-form-item label="简介" prop="content">
            <el-input v-model="formData.content"></el-input>
          </el-form-item>

          <el-form-item label="列表图片数量" prop="imgCount" >
            <el-radio-group v-model="formData.imgCount" @change="changeImgCount" >
              <el-radio :label="0">0</el-radio>
              <el-radio :label="1">1</el-radio>
              <el-radio :label="3">3</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item  label="列表图片" prop="imgarr" >
            <div class="image-box" v-for="(e, i) in formData.imgarr" :key="i">
              <img :src="e" alt="" height="100" style="margin-right: 8px;">
              <i class="el-icon-delete" @click="delImage(i)"></i>
            </div>
            <el-upload
              class="avatar-uploader"
              action="#"
              v-show="formData.imgarr.length < 3"
              :show-file-list="false"
              :before-upload="beforeUpload2">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="是否热门" prop="ishot" >
            <el-radio-group v-model="formData.ishot">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <template v-if="!isAdd">
            <el-form-item label="点赞数" prop="fabulous">
              <el-input v-model.number="formData.fabulous"></el-input>
            </el-form-item>

            <el-form-item label="被踩数" prop="trampled">
              <el-input v-model.number="formData.trampled"></el-input>
            </el-form-item>

            <el-form-item label="收藏量" prop="collcount">
              <el-input v-model.number="formData.collcount"></el-input>
            </el-form-item>

            <el-form-item label="阅读量" prop="clickcount">
              <el-input v-model.number="formData.clickcount"></el-input>
            </el-form-item>

            <!-- <el-form-item label="评论量"  prop="commentcount">
              <el-input v-model.number="formData.commentcount"></el-input>
            </el-form-item> -->
          </template>

          <el-form-item label="富文本详情" prop="profiles" >
            <wangEditor :catchData="catchData" ref="editor" ></wangEditor>
          </el-form-item>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="showAdd = false">取 消</el-button>
          <el-button type="primary" @click="handleClickSendForm('richForm')" :loading="loading">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="评论"
        :visible.sync="commentShow"
        width="70%">
        <el-table :data='tableCommentData' style='width: 100%'>
          <el-table-column type="index" label='序号' ></el-table-column>
          <el-table-column prop='content' label='评论内容' ></el-table-column>
          <el-table-column prop='createtime' label='创建时间' ></el-table-column>
          <el-table-column prop='name' label='用户名称'></el-table-column>
          <el-table-column prop='fabulous' label='点赞量'></el-table-column>
          <el-table-column prop='avatar' sortable label='头像' >
            <template slot-scope="scope">
              <img :src="scope.row.avatar" width="50" />
            </template>
          </el-table-column>
          <el-table-column prop='isbusiness' sortable label='是否商家' >
            <template slot-scope="scope">
              <span v-if="!Number(scope.row.isbusiness)">否</span>
              <span v-if="Number(scope.row.isbusiness)">是</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            background
            @size-change="handleCommentSizeChange"
            @current-change="handleCommentCurrentChange"
            :current-page="commentPage.page"
            :page-sizes="[20, 50, 100]"
            :page-size="commentPage.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="commentPage.total">
          </el-pagination>
        </div>

        <span slot="footer" class="dialog-footer">
          <span> </span>
        </span>
      </el-dialog>
  </div>
</template>
<script>
import utils from '@/utils/utils'
import wangEditor from '../common/wangEditor'
export default {
  name: 'richText',
  data () {
    var checkNumber = (rule, value, callback) => {
      if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'))
      } else {
        if (value < 0) {
          callback(new Error('请输入大于等于0的值'))
        } else {
          callback()
        }
      }
    }
    var checkCImg = (rule, value, callback) => {
      if (JSON.stringify(this.formData['imgarr']) === '[]' && (this.formData['imgCount'] !== 0 && this.formData['imgCount'] !== '0')) {
        return callback(new Error('列表图片数量不为空'))
      } else if (this.formData['imgarr'].length < this.formData['imgCount']) {
        return callback(new Error('列表图片数量应为' + this.formData['imgCount']))
      } else {
        callback()
      }
    }
    return {
      tableData: [],
      tableCommentData: [],
      commentShow: false,
      commentPage: {
        page: 1,
        size: 20,
        total: 1
      },
      loading: false,
      memberArr: [],
      formData: {
        id: '',
        memberid: '',
        membername: '',
        title: '',
        content: '',
        imgCount: '',
        imgarr: [],
        ishot: '',
        profiles: '',
        fabulous: 0,
        commentcount: 0,
        clickcount: 0,
        collcount: 0,
        trampled: 0
      },
      rules: {
        memberid: [
          { required: true, message: '请选择发布人', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入帖子简介', trigger: 'blur' }
        ],
        imgCount: [
          { required: true, message: '请选择列表图片数量', trigger: 'blur' }
        ],
        ishot: [
          { required: true, message: '请选择是否热门', trigger: 'blur' }
        ],
        profiles: [
          { required: true, message: '请输入帖子内容', trigger: 'blur' }
        ],
        fabulous: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        commentcount: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        clickcount: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        collcount: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        trampled: [
          { required: true, message: '请输入', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        imgarr: [
          { validator: checkCImg, trigger: 'blur' }
        ]
      },
      isAdd: false,
      showAdd: false,
      searchItems: [
        {
          label: '发布人',
          type: 'input',
          key: 'membername'
        },
        {
          label: '发布时间',
          type: 'times',
          key: 'createtime'
        },
        {
          label: '标题',
          type: 'input',
          key: 'title'
        },
        {
          label: '是否热门',
          type: 'select',
          key: 'ishot',
          options: [{ id: '1', name: '是' }, { id: '0', name: '否' }]
        }
      ],
      page: {
        page: 1,
        size: 20,
        total: 1
      },
      sortVal: {}
    }
  },
  methods: {
    getList () {
      let searchData = {}
      if (this.$refs['search']) {
        searchData = this.$refs['search'].search()
      }
      if (searchData.createtime) {
        searchData.starttime = searchData.createtime.split(',')[0]
        searchData.endtime = searchData.createtime.split(',')[1]
        searchData.createtime = ''
      }
      let params = {
        ...searchData,
        page: this.page.page,
        size: this.page.size
      }
      if (this.sortVal.prop) {
        params.orderby = this.sortVal.prop + ' ' + this.sortVal.order
      }
      this.axios.get('/Richarticle/index', { params }).then(res => {
        if (res.data.status === '1' || res.data.status === 1) {
          let arr = ['fabulous', 'trampled', 'commentcount', 'collcount', 'clickcount']
          utils.tableItemToNumber(res.data.data.list, arr)
          this.page.total = Number(res.data.data.count)
          this.tableData = res.data.data.list
        }
      })
    },
    handleSizeChange (val) {
      this.page.size = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.page.page = val
      this.getList()
    },
    handleCommentSizeChange (val) {
      this.commentPage.size = val
      this.getList()
    },
    handleCommentCurrentChange (val) {
      this.commentPage.page = val
      this.getList()
    },
    handleClickDeleteItem (e = 1, val) {
      let self = this
      let params = {}
      params.id = val
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/Richarticle/delete', { params: {id: val} }).then(res => {
          if (res.data.status) {
            self.$message({
              message: '删除成功',
              type: 'success'
            })
            self.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleClickEditItem (id = false) {
      this.loading = false
      // /Richarticle/detail
      // this.$refs['editor'].setData(res.data.data.luckdrawcontent)
      this.cleanForm()
      let self = this
      let params = {}
      if (id) {
        params.id = id
      }
      this.axios.get('/Richarticle/detail', { params }).then(res => {
        if (res.data.status === 1 || res.data.status === '1') {
          for (let key in self.formData) {
            self.formData[key] = res.data.data[key]
          }
          this.formData['fabulous'] = Number(res.data.data['fabulous'])
          this.formData['commentcount'] = Number(res.data.data['commentcount'])
          this.formData['clickcount'] = Number(res.data.data['clickcount'])
          this.formData['collcount'] = Number(res.data.data['collcount'])
          this.formData['trampled'] = Number(res.data.data['trampled'])
          this.formData['ishot'] = Number(res.data.data['ishot'])
          console.log(!this.formData.imgarr)
          if (this.formData.imgarr) {
            this.formData.imgCount = this.formData.imgarr.length
          } else {
            this.formData.imgCount = 0
            this.formData.imgarr = []
          }
          this.$refs['editor'].setData(self.formData.profiles)
        }
      })
      this.showAdd = true
      this.isAdd = false
    },
    hanldeClickCheckItem (parid = false, isFirst = true) {
      let self = this
      this.commentShow = true
      if (isFirst) {
        this.commentPage.page = 1
        this.commentPage.size = 20
      }
      let params = {
        type: 5,
        parid,
        page: self.commentPage.page,
        size: self.commentPage.size,
        ordertype: 1
      }
      this.axios.get('/Comment/getcomment', { params }).then(res => {
        if (res.data.status === 1 || res.data.status === '1') {
          this.commentPage.total = res.data.data.count
          this.tableCommentData = res.data.data.list
        }
      })
    },
    beforeUpload2 (file) {
      this.imageUrl = URL.createObjectURL(file)
      let _self = this
      let reader = new FileReader()
      reader.onload = function (ev) {
        _self.formData.imgarr.push(ev.currentTarget.result)
      }
      reader.readAsDataURL(file)
      return false
    },
    delImage (index) {
      this.formData.imgarr.splice(index, 1)
    },
    handleClickChangeContent () {
      let self = this
      let params = {}
      params.profiles = this.formData.profiles
      this.axios.post('/Luckdraw/editagreement', self.qs.stringify(params)).then(res => {
        if (res.data.status === 1 || res.data.status === '1') {
          self.$message({
            message: '修改成功',
            type: 'success'
          })
          self.getList()
        }
      })
    },
    catchData (val) {
      this.formData.profiles = val
    },
    getMember (query = false) {
      this.loading = true
      let params = {
        page: 1,
        size: 15,
        type: 3
      }
      if (query) {
        params.membername = query
      }
      this.axios.get('/type/getmemberarr', { params }).then(res => {
        if (res.data.status === 1 || res.data.status === '1') {
          this.memberArr = res.data.data.list
          this.loading = false
        }
      })
    },
    resetForm (formName) { // 重置验证
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
    },
    cleanForm () { // 初始化表单数据
      let self = this
      for (let key in self.formData) {
        if (key !== 'imgarr') {
          self.formData[key] = ''
        }
      }
      if (this.$refs['editor']) {
        this.$refs['editor'].setData('')
      }
      this.formData.imgarr = []
      this.resetForm('richForm')
    },
    handleClickSendForm (formName) {
      let url = this.isAdd ? '/Richarticle/add' : '/Richarticle/edit'
      let self = this
      this.loading = true
      if (this.formData.imgarr.length !== this.formData.imgCount) {
        self.$message({
          message: '请选择与列表图片数量相同数量的列表图片',
          type: 'error'
        })
        this.loading = false
        return false
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {}
          for (let key in self.formData) {
            if (key !== 'id') {
              if (self.formData[key] !== '') {
                params[key] = self.formData[key]
              }
            }
          }
          if (!self.isAdd) {
            params['id'] = self.formData.id
          }
          this.axios.post(url, self.qs.stringify(params)).then(res => {
            if (res.data.status === 1 || res.data.status === '1') {
              self.$message({
                message: '成功',
                type: 'success'
              })
              self.showAdd = false
              this.loading = false
              self.getList()
            }
          })
        } else {
          return false
        }
        setTimeout(() => {
          self.loading = false
        }, 5000)
      })
    },
    changeImgCount (val) {
      if (this.formData.imgarr.length > val) {
        this.formData.imgarr = this.formData.imgarr.splice(0, val)
      }
    },
    sortChange (data) {
      console.log(data)
      this.sortVal.prop = data.prop
      if (data.order === 'ascending') {
        this.sortVal.order = 'asc'
      } else if (data.order === 'descending') {
        this.sortVal.order = 'desc'
      } else {
        this.sortVal.order = ''
      }
      this.getList()
    }
  },
  mounted () {
    this.getList()
    this.getMember()
  },
  components: {
    wangEditor
  }
}
</script>
<style scoped>
@import "../../assets/css/style.css";
</style>
